//
//  QDDateDoctorController.m
//  simulateQuickDoctor
//
//  Created by 梁家伟 on 17/3/25.
//  Copyright © 2017年 PipiXia. All rights reserved.
//

#import "QDDateDoctorController.h"
#import "MyIndexView.h"
#import <UIImageView+WebCache.h>
#import "QDDateDoctorTextCell.h"
#import "QDNetworkTool.h"
#import "QDPageDetailController.h"
#import "QDBannerTools.h"

#define IndeViewHeight 50
#define TopViewHeight 130

@interface QDDateDoctorController ()<UIPageViewControllerDataSource,UIPageViewControllerDelegate>
@property(nonatomic,weak)UIView* topView;
@property(nonatomic,weak)MyIndexView* indexView;
@property(nonatomic,weak)UIImageView* iconImageView;
@property(nonatomic,weak)UILabel* nameLabel;
@property(nonatomic,weak)UILabel* titleLabel;
@property(nonatomic,weak)UILabel* hospitalLabel;
@property(nonatomic,weak)UIButton* accuracyButton;
@property(nonatomic,weak)UILabel* bookCountLabel;
@property(nonatomic,weak)UIButton* flowerCountBtn;
@property(nonatomic,weak)UIButton* flagCountBtn;
@property(nonatomic,strong)UIPageViewController* pageVC;
@property(nonatomic,strong)UIButton* attentionButton;
@property(nonatomic,assign)BOOL isAttent;
@end

@implementation QDDateDoctorController{
    NSMutableArray<NSDictionary*>* _dataDictArr;
    NSUInteger _currentIndex;
}

static NSString* textCell = @"text";

- (instancetype)init{
    
    if(self = [super init]){
        
        _dataDictArr = [NSMutableArray array];
        _isAttent = YES;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self loadData];
}

- (void)setupUI{
    
//     self.automaticallyAdjustsScrollViewInsets = NO;
    
    if([self.parameters[@"entrance"] isEqualToString:@"doctorAttention"]){
       
        _isAttent = YES;
        
        UIBarButtonItem* rightBarBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"saveTemplate"] style:UIBarButtonItemStylePlain target:self action:@selector(doctorAttent:)];
        
        self.navigationItem.rightBarButtonItem = rightBarBtn;
    }
    
    
    //设置顶部视图
    [self setupTopView];
    
    [self setupCategoryView];
    
    self.navigationItem.title = @"医生详情";
    
//    self.view.backgroundColor = [UIColor whiteColor];
    [self setupPageView];
    
   
    
}


/**
 关注医生

 @param sender 点击关注
 */
- (void)doctorAttent:(UIBarButtonItem*)sender{
    
    _isAttent = !_isAttent;
    
    if(_isAttent){
        sender.image = [UIImage imageNamed:@"saveTemplate"];
    }else{
        sender.image = [UIImage imageNamed:@"saveTemplateEmpty"];
    }
    
    [self attentDoctorWithType:_isAttent];
}


/**
 发送关注
 */
- (void)attentDoctorWithType:(BOOL)type{
    
    NSString* urlString = nil;
    
    if(type){
        urlString = @"http://iosapi.itcast.cn/doctor/addDoctor.json.php";
    }else{
        urlString = @"http://iosapi.itcast.cn/doctor/deleteDoctor.json.php";
    }
    
    QDNetworkTool* tool = [QDNetworkTool sharedTool];
    
    NSDictionary *postParams = @{@"user_id":@1000089,@"doctor_id":@300000315};
    
    
    NSLog(@"params = %@",postParams);
    
    
    tool.requestSerializer = [AFJSONRequestSerializer serializer];
    [tool requestWithHTTPMethod:@"POST" URLString:urlString parameters:postParams CallBack:^(id responseObj) {
        
        if(responseObj != nil){
            
            NSString* result = responseObj[@"msg"]; //FAIL
            
            if([result isEqualToString:@"OK"]){
                
//                NSDictionary* dict = responseObj[@"data"];
                
                
                [QDBannerTools pp_BannerSuccessTitle:type == YES ?@"成功关注":@"取消关注" andTime:1.0];
                
                
            }else{
                NSLog(@"请求参数错误");
            }
            
        }else{
            NSLog(@"网络请求错误");
        }
    }];
    
}

- (void)setupPageView{
    
    UIView* pageParentView = [[UIView alloc]init];
    [self.view addSubview:pageParentView];
    [pageParentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(_indexView.mas_bottom);
    }];
    
    UIPageViewController* pageVC = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    

    _pageVC = pageVC;
    pageVC.dataSource = self;
    pageVC.delegate = self;
    
    QDPageDetailController* detailVC = [[QDPageDetailController alloc]initWithIndex:0];
    
    [pageVC setViewControllers:@[detailVC] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    
    [self addChildViewController:pageVC];
//    [self.view addSubview:pageVC.view];
    [pageParentView addSubview:pageVC.view];
    
    [pageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.bottom.right.equalTo(self.view);
//        make.top.equalTo(_indexView.mas_bottom);
        make.edges.equalTo(pageParentView);
    }];
 
    [pageVC didMoveToParentViewController:self];
    
    
}

- (void)setupCategoryView{
    MyIndexView* indexView = nil;
    if([self.parameters[@"entrance"] isEqualToString:@"doctorApply"]){
        indexView = [[MyIndexView alloc]initWithData:@[@"接诊条件",@"医生简介",@"预约时间"]];
    }else{
        indexView = [[MyIndexView alloc]initWithData:@[@"接诊条件",@"医生简介"]];
    }
    _indexView = indexView;
    [self.view addSubview:indexView];
    [indexView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(_topView.mas_bottom);
        make.height.offset(50);
    }];
    
    [_indexView addTarget:self action:@selector(changeItem:) forControlEvents:UIControlEventValueChanged];
}

-(void)changeItem:(MyIndexView*)sender{
    
    NSUInteger idx = sender.tag;
    
    QDPageDetailController* detailVC = [[QDPageDetailController alloc]initWithIndex:idx];

    
    if(idx == _currentIndex){
        
    }else if(idx > _currentIndex){
        
        [_pageVC setViewControllers:@[detailVC] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    }else{
        
        [_pageVC setViewControllers:@[detailVC] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:nil];
    }
    
    _currentIndex = idx;
    _indexView.index = _currentIndex;
}


- (void)setupTopView{
    
    UIView * topView = [[UIView alloc]init];
    _topView = topView;
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.offset(130);
    }];
    
    
    //头像
    UIImageView* iconImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"doctor_defaultphoto_male"]];
    
    [topView addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(topView).offset(25);
        make.top.equalTo(topView).offset(12);
        make.size.mas_equalTo(CGSizeMake(66, 66));
    }];
    
    
    
    //姓名
    UILabel* nameLabel = [UILabel cz_labelWithText:@"姓名" fontSize:18 color:[UIColor blackColor]];
    [topView addSubview:nameLabel];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconImageView);
        make.left.equalTo(iconImageView.mas_right).offset(12);
    }];
    
    
    //职称
    UILabel* titleLabel = [UILabel cz_labelWithText:@"职称" fontSize:15 color:[UIColor blackColor]];
    [topView addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconImageView).offset(3);
        make.left.equalTo(nameLabel.mas_right).offset(12);
    }];
    
    
    //医院
    UILabel* hospitalLabel = [UILabel cz_labelWithText:@"中医院肿瘤科" fontSize:15 color:[UIColor lightGrayColor]];
    [topView addSubview:hospitalLabel];
    
    [hospitalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameLabel.mas_bottom).offset(8);
        make.left.equalTo(nameLabel);
    }];
    
    
    //精确率
    UIButton* accuracyButton = [[UIButton alloc]init];
    [accuracyButton setBackgroundImage:[UIImage imageNamed:@"pipeidu"] forState:UIControlStateNormal];
    accuracyButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [accuracyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [accuracyButton setTitle:@"98%" forState:UIControlStateNormal];
    [topView addSubview:accuracyButton];
    
    accuracyButton.enabled = NO;
    [accuracyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconImageView);
        make.right.equalTo(topView).offset(-32);
    }];
    
    //预约数
    UILabel* bookCountLabel = [UILabel cz_labelWithText:@"预约数:2" fontSize:15 color:[UIColor blackColor]];
    [topView addSubview:bookCountLabel];
    [bookCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconImageView.mas_bottom).offset(14);
        make.left.equalTo(topView).offset(50);
    }];
    
    //鲜花数
    UIButton* flowerCountBtn = [UIButton cz_textButton:@" 鲜花数:2" fontSize:15 normalColor:[UIColor blackColor] selectedColor:[UIColor blackColor]];
    flowerCountBtn.enabled = NO;
    [topView addSubview:flowerCountBtn];
    [flowerCountBtn setImage:[UIImage imageNamed:@"xianhua"] forState:UIControlStateNormal];
    
    [flowerCountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bookCountLabel.mas_right).offset(8);
        make.top.equalTo(bookCountLabel.mas_top);
    }];
    //锦旗数
    UIButton* flagCountBtn = [UIButton cz_textButton:@" 锦旗数:2" fontSize:15 normalColor:[UIColor blackColor] selectedColor:[UIColor blackColor]];
    [topView addSubview:flagCountBtn];
    flagCountBtn.enabled = NO;
    [flagCountBtn setImage:[UIImage imageNamed:@"jinqi"] forState:UIControlStateNormal];
    
    [flagCountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(flowerCountBtn.mas_right).offset(24);
        make.right.equalTo(topView).offset(-50);
        make.top.equalTo(bookCountLabel.mas_top);
    }];
    
    
    _titleLabel = titleLabel;
    _nameLabel = nameLabel;
    _iconImageView = iconImageView;
    _hospitalLabel = hospitalLabel;
    _accuracyButton = accuracyButton;
    _bookCountLabel = bookCountLabel;
    _flagCountBtn = flagCountBtn;
    _flowerCountBtn =flowerCountBtn;
    
}

- (void)loadData{
    
    _titleLabel.text = self.model.doctor_title_name;
    _nameLabel.text = self.model.doctor_name;
    [_iconImageView sd_setImageWithURL:[NSURL URLWithString:self.model.doctor_portrait] placeholderImage:[UIImage imageNamed:@"doctor_defaultphoto_male"]];
    
    [self clipIcon:_iconImageView];
    
    _hospitalLabel.text = self.model.doctor_hospital_name;
    [_accuracyButton setTitle:self.model.accuracy forState:UIControlStateNormal];
    _bookCountLabel.text = [NSString stringWithFormat:@"预约数:%zd",self.model.operation_count];
    [_flowerCountBtn setTitle:[NSString stringWithFormat:@" 鲜花数:%zd",self.model.flower] forState:UIControlStateNormal];
    [_flagCountBtn setTitle:[NSString stringWithFormat:@" 锦旗数:%zd",self.model.banner] forState:UIControlStateNormal];
    
    
}

#pragma -mark 头像切圆

- (void)clipIcon:(UIImageView*)imageView{
    
    
    //加载图片
    UIImage *image = imageView.image;
    
    //获取图片尺寸
    CGSize size = image.size;
    
    //开启位图上下文
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    //创建圆形路径
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    
    //设置为裁剪区域
    [path addClip];
    
    //绘制图片
    [image drawAtPoint:CGPointZero];
    
    //获取裁剪后的图片
    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    
}

#pragma -mark 代理方法

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers{
    
    QDPageDetailController * newListVC = (QDPageDetailController *)pageViewController.viewControllers[0];
   _indexView.index = newListVC.index;
}


- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed{
    
   QDPageDetailController * newListVC = (QDPageDetailController *)pageViewController.viewControllers[0];
    _indexView.index = newListVC.index;
}


#pragma -mark 数据源方法



- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(QDPageDetailController *)viewController{
    
    if(viewController.index== 0){
        return nil;
    }
    
    NSUInteger newIndex = viewController.index - 1;
    
    QDPageDetailController* detailVC = [[QDPageDetailController alloc]initWithIndex:newIndex];
    
    _currentIndex = newIndex;
    return detailVC;
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(QDPageDetailController *)viewController{
    
    if(viewController.index == _indexView.maxCount){
        return nil;
    }
    
    NSUInteger newIndex = viewController.index + 1;
    
    QDPageDetailController* detailVC = [[QDPageDetailController alloc]initWithIndex:newIndex];
    
    _currentIndex = newIndex;
    return detailVC;
}


@end
